/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.support.transform.xml;

import cn.easyplatform.support.transform.AbstractTransformer;
import cn.easyplatform.support.transform.Parameter;
import cn.easyplatform.support.transform.TagNode;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class XmlToTableTransformer extends
        AbstractTransformer<Document, Map<String, List<TagNode>>> {

    private Map<String, List<TagNode>> tags = new HashMap<String, List<TagNode>>();

    @SuppressWarnings("unchecked")
    @Override
    public void transform(Document doc, Parameter parameter) {
        TagNode root = new TagNode(doc.getRootElement().getName()).setPath("/"
                + doc.getRootElement().getName());
        tags.put("", new ArrayList<TagNode>());
        tags.get("").add(root);
        parse(root, doc.getRootElement().elements());
        handler.transform(tags, parameter);
    }

    @SuppressWarnings("unchecked")
    private void parse(TagNode parent, List<Element> elements) {
        for (Element elm : elements) {
            if (elm.elements().isEmpty()) {
                TagNode node = new TagNode(elm.getName()).setValue(elm
                        .getText().trim());
                parent.appendChild(node);
            } else {
                TagNode node = new TagNode(elm.getName()).setPath(parent
                        .getPath() + "/" + elm.getName());
                parent.appendChild(node);
                List<TagNode> nodes = tags.get(node.getPath());
                if (nodes == null) {
                    nodes = new ArrayList<TagNode>();
                    tags.put(node.getPath(), nodes);
                }
                nodes.add(node);
                parse(node, elm.elements());
            }
        }
    }

}
